package com.nf.health.app.datamain.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.customview.BrokenLine;
import com.nf.health.app.customview.MenuPopupWindow;
import com.nf.health.app.models.BloodoHistoryOygenBean;
import com.nf.health.app.models.BloodoOygenBean;
import com.nf.health.app.models.BluetoothDeviceAttr;
import com.nf.health.app.models.DataDetails;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.models.OxyDeviceDataBean;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ByteUtils;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bluetools.ProtocolParser;

/**
 * 血氧页面
 * Created by Administrator on 2016/5/24.
 */
public class  BloodOxygenActivity extends BaseActivity {
    private final String OXYGENTION_HISTORY = "com.nf.health.app.activity.history";
    public static final String ACTION_OXYGENTION_HISTORY = "action.com.nf.health.app.activity.history";
    /**
     * 标记TAB
     */
    private int currentIndex = 0;

    //扫描间隔5s
    private static final long INTERVAL_TIME = 5 * 1000;
    @Bind(R.id.iv_progress)//大圆圈
            ImageView ivProgress;
    @Bind(R.id.iv_type_icon)//选中的图片
            ImageView ivTypeIcon;
    @Bind(R.id.tv_type_value)//选中的数值
            TextView tvTypeValue;
    @Bind(R.id.tv_type_name)//选中的 名称
            TextView tvTypeName;
    @Bind(R.id.tv_bluetooth)//连接图标 已取消
            TextView tvBluetooth;
    @Bind(R.id.rb_oxy_sop)//sop按钮
            RadioButton rbOxySop;
    @Bind(R.id.rb_oxy_mb)//脉搏按钮
            RadioButton rbOxyMb;
    @Bind(R.id.rg_bracelet_navigator)//rg初始化
            RadioGroup rgBraceletNavigator;
    @Bind(R.id.tv_tab_high)//spo值  id没改
            TextView tvTabHigh;
    @Bind(R.id.tv_tab_low)//脉搏值 id没改
            TextView tvTabLow;
    @Bind(R.id.history_text)//历史记录text
            TextView historyText;
    @Bind(R.id.tv_unit)//线形图单位
            TextView tvUnit;
    @Bind(R.id.rl_broken_line)//线形图 布局Lin
            LinearLayout rlBrokenLine;
    @Bind(R.id.btn_start_measure)//开始测量按钮
            Button btnStartMeasure;

    // 蓝牙服务类
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothAdapter mBluetoothAdapter;
    // 蓝牙服务类
    private BluetoothLeService mBluetoothLeService;
    private List<BluetoothDevice> devices = new ArrayList<>();

    private ServiceConnection mServiceConnection;
    private ArrayList<byte[]> listData = new ArrayList<>();//请求储存的对象
    private ArrayList<BloodoOygenBean> listBean = new ArrayList<>();//存储解析完的对象
    private List<DataDetails> dataDetails = new ArrayList<>();

    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.rl_history)
    RelativeLayout rl_history;
    /******x轴(折线)********/
    private ArrayList<String>listXOxyGen = new ArrayList<>();
    /**********y轴(折线)******/
    private ArrayList<Float> listYOxyGen = new ArrayList<>();
    private ArrayList<Float> listYHeartRate = new ArrayList<>();
    TimeCount timeCount;
    private boolean isTimeFinish = true;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_blood_oxygen);

        ButterKnife.bind(this);

        initListener();

        initBluetooth();

        ViewUtil.setText(this, R.id.titlebar_title_tv, "血氧数据");
        titlebarRightView.setVisibility(View.VISIBLE);
        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.ic_title_setting);
        IntentFilter intentFilter= BluetoothLeService.makeGattUpdateIntentFilter();
        intentFilter.addAction(ACTION_OXYGENTION_HISTORY);
        registerReceiver(mGattUpdateReceiver, intentFilter );
        timeCount = new TimeCount(5 * 1000, 1000);

    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        public static final String TAG = "mGattUpdateReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                // tvBluetooth.setText("(已连接)");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                showToast("蓝牙连接断开,请重试");
                // tvBluetooth.setText("(未连接)");
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        mBluetoothLeService.starToxygenTest();
                    }
                }, 500);

            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (data == null) {
                    return;
                }
                LogUtil.e(TAG, ProtocolParser.binaryToHexString(data) + ">>>>" + data.length);
                try {
                    handleBloodPressureData(data);
                } catch (Exception e) {
                    LogUtil.exception(e);
                }
            }else if (ACTION_OXYGENTION_HISTORY.equals(action)) {
                BloodoOygenBean modele = (BloodoOygenBean) intent.getSerializableExtra("getOxygenDate");
                if(modele != null){
                    tvTabHigh.setText(modele.getOxygenValue() + "");//赋值
                    tvTabLow.setText(modele.getHeartRate()+ "");//赋值
                    tvTypeValue.setText(modele.getOxygenValue()  + "");
                }else{
                    tvTabHigh.setText(0+ "");//赋值
                    tvTabLow.setText(0+ "");//赋值
                    tvTypeValue.setText(0+ "");
                }
            }
        }
    };

    /*****解析并校验*******/
    private void handleBloodPressureData(byte[] data) {
        if(data[0] == -86 || data[0] == 0XAA){
            if(listData == null || listData.size() == 0){//如果集合不为空,则进一步校验
            }else{
                //得到最后一位数组
                byte[] lastData = listData.get(listData.size() - 1);
                //去除校验位,即最后一位
                if(lastData != null && lastData.length >= 2){
                    ArrayList<byte[]> getSubListData =  ByteUtils.updateSubLkastListByte(listData);
                }if(lastData.length == 1){
                    listData.remove(listData.size() - 1);
                }
              /* for (int i = 0; i <listData.size() ; i++) {
                    LogUtil.e("最终结果: " + ProtocolParser.binaryToHexString(listData.get(i)) + ">>>>" + listData.get(i).length);
                }*/

                //进行校验,累加求和 %256  余校验位进行比较,看看是不是之和与第二位相等,相等的话,则是正确的数据,不等的话将其过滤掉
                //float ff = ByteUtils.getListByteTotle(listData);
                float ff = ByteUtils.getListAllByteTotle(listData);
                if(lastData[lastData.length - 1] == (ff%256)){
                    //向大集合和里面添加
                    // 1.过滤有用数据
                    listBean.add(null);
//                    LogUtil.e(lastData[lastData.length - 1] + "最终求和结果: " + ProtocolParser.binaryToHexString(listData.get(0)) + ">>>>" + listData.get(0).length);
                    //LogUtil.e(lastData[lastData.length - 1] + "最终求和结果: " + ff+"  校验位: "  + lastData[lastData.length - 1]+"    "+ProtocolParser.binaryToHexString(lastData) + ">>>>" + lastData.length);
//                    LogUtil.e(lastData[lastData.length - 1] + " ------ " + (ff%256));
                    //int response = java.lang.Integer.toHexString(90);ProtocolParser.byteArrayReverse(listData.get(0))[0];
                    //获取数据块: 取出命令字段
                    byte response = listData.get(0)[1];
                    switch (response){
                        case 0x03:  //响应状态
                            break;
                        case 0x41:  //血氧数据包（蓝牙血氧使用）
                        {
                            //先转化为数组的形式
                            LogUtil.e(" ------ " + response + "" + (response == 0x41));
                            //正常范围：0~100 无效值：127 呼吸率  (由于包括了数据长度,所以讲 34加1 ,35加1)
                            //int oxygenValue = ByteUtils.getByteFromListBytes(listData, 35);//血痒值
                            int oxygenValue =  listData.get(1)[16];//血痒值
                            String currentTime =  DateUtil.getCurrentDate2() ;//获取当前的时间
                            //脉率范围：0~254 无效值：255
                            int heartRate =  listData.get(1)[17];//脉率值
                            //int heartRate = ByteUtils.getByteFromListBytes(listData,36);//脉率值
                            if (oxygenValue<=100 && oxygenValue>0 && heartRate>0 && heartRate<255 ) {
                                LogUtil.e("",oxygenValue+ " ----- " +heartRate+"  " + ByteUtils.getByteFromListBytes(listData,35));
                                BloodoOygenBean model = new BloodoOygenBean();
                                model.setCurrentTime(currentTime);
                                model.setHeartRate(heartRate);
                                model.setOxygenValue(oxygenValue);
                                //数据采集成功。通知控制器
                                final Intent intent = new Intent(BloodOxygenResultyActivity.REFRESH_BROADCAST_MEASUREE_OXYGEN);
                                intent.putExtra(BloodOxygenResultyActivity.REFRESH_BROADCAST_MEASUREE_OXYGEN, model);
                                if(isTimeFinish){
                                    sendBroadcast(new Intent(intent));
                                    timeCount.start();
                                }
                               /* mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            new Thread().sleep(300);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        sendBroadcast(new Intent(intent));
                                    }
                                }, 1000);*/

                            }
                        }
                        break;
                        case 0x42:  //请求重发数据不存在报文（波形传输用）
                            break;
                        case 0x43:  //血氧状态包
                            break;
                        default:
                            break;
                    }
                }
            }
            //如果有以aa开头说明是新一段数据,则清空集合
            listData.clear();
            //去除数组的aa,,保留有用的集合 //校验字节，为包头和Checksum字节间所有数据的累加校验和。
            byte[] subUserByte =  ByteUtils.subStartByte(data,1);
            listData.add(subUserByte);
        }else {//if(data[0] != 0X00)
            listData.add(data);
        }
    }


    /********
     * 初始化蓝牙
     *******/
    private void initBluetooth() {
        // 检查当前手机是否支持blue 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持蓝牙4.0通讯");
            return;
        }
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            showToast("没有发现蓝牙模块");
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (device != null) {
                                if (!TextUtils.isEmpty(device.getName())) {
                                    // devices.add(device);
                                    String name = device.getName();
                                    if (name.contains(BluetoothDeviceAttr.OYGEN_DEVICE_NAME)) {
                                        if (!devices.contains(device)) {
                                            devices.add(device);
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            };
        } else {
            showToast("设备蓝牙版本过低");
            finish();
            return;
        }
        bindLeService();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                if (!mBluetoothLeService.initialize()) {
                    new MaterialDialog.Builder(BloodOxygenActivity.this)
                            .title("提示")
                            .content("蓝牙初始化服务失败了~")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    finish();
                                }
                            })
                            .show();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bleService.putExtra("type", DeviceData.Type.OXYGEN);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        historyText.setOnClickListener(this);
        btnStartMeasure.setOnClickListener(this);
        rl_history.setOnClickListener(this);
        historyText.setOnClickListener(this);

        rgBraceletNavigator.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                currentIndex = checkedId;
                resetTabValue();
            }
        });
        //历史数据
        historyText.setOnClickListener(this);
        initData();
    }


    private void resetTabValue() {
        switch (currentIndex) {
            case R.id.rb_oxy_sop://血痒值  0
                tvTabHigh.setTextColor(Color.parseColor("#FFF36A"));
                tvTabLow.setTextColor(Color.parseColor("#FFFFFF"));
                tvTypeName.setText("SPO2");
                tvUnit.setText("单位: %");
                ivTypeIcon.setImageResource(R.drawable.ic_oxy_spo_image);
                refreshView(listXOxyGen,listYOxyGen,currentIndex);
                break;
            case R.id.rb_oxy_mb://脉搏值 1
                tvTabHigh.setTextColor(Color.parseColor("#FFFFFF"));
                tvTabLow.setTextColor(Color.parseColor("#FFF36A"));
                tvTypeName.setText("脉搏");
                tvUnit.setText("单位: 次/分钟");
                ivTypeIcon.setImageResource(R.drawable.ic_oxy_mb_image);
                refreshView(listXOxyGen,listYHeartRate,currentIndex);
                break;
        }
    }
    public void refreshView(ArrayList<String> listX,ArrayList<Float> listY,int position) {
        //若没有测过,返回
        if (listX == null | listY == null){
            return ;
        }
        if (listX.size() == 0 || listY.size() == 0) {
            return;
        }
        rlBrokenLine.removeAllViews();
        tvTypeValue.setText(listY.get(0)+ "");
        if(currentIndex == R.id.rb_oxy_sop){
            rlBrokenLine.addView(new BrokenLine(BloodOxygenActivity.this, listX, listY, 100, 0, 1, 90));
        }else{
            rlBrokenLine.addView(new BrokenLine(BloodOxygenActivity.this, listX, listY, 200, 0, 1, 60));
        }
    }
    private void initData() {
        currentIndex = R.id.rb_oxy_sop ;
        resetTabValue();//初始化 默认是血痒
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //右边按钮的点击事件
            case R.id.titlebar_right_view:
                showPop();
                break;
            case R.id.btn_start_measure://测量

                //如果没有绑定设备，则先进行搜索
                if (PreferenceHelper.getBoolean(PreferenceHelper.Oxygen_IS_BING, false)) {
                    String selectOxgenName = PreferenceHelper.getString(PreferenceHelper.Oxygen_ADDRESS, "");
                    if(selectOxgenName.contains("血氧仪-") || selectOxgenName.startsWith("血氧仪-")){
                        selectOxgenName = selectOxgenName.replace("血氧仪-","");
                    }
//                    if (BluetoothLeService.isConnected) {
                        measureDataByMeachine(selectOxgenName);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ActivityUtils.showActivity(BloodOxygenActivity.this,BloodOxygenResultyActivity.class);
                            }
                        }, 500);
//                    } else {

                        measureDataByMeachine(selectOxgenName);
                       // scanLeDevice(true);
//                    }
                } else {
                    showPop();
                }
                break;
            case R.id.rl_history://进入历史记录
                ActivityUtils.showActivity(BloodOxygenActivity.this, BloodOxygenHistoryActivity.class);
                //历史记录所需参数
                break;
            case R.id.history_text://进入历史记录
                ActivityUtils.showActivity(BloodOxygenActivity.this, BloodOxygenHistoryActivity.class);
                //历史记录所需参数
                break;
            default:
                break;
        }
    }
    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (OXYGENTION_HISTORY.equals(actionName)) {
            provider.requestAddScore("19", "");//添加积分
            BloodoHistoryOygenBean bloodoHistoryOygenBean = (BloodoHistoryOygenBean) object;
            ArrayList<OxyDeviceDataBean> getlist = bloodoHistoryOygenBean.getDeviceData();
            //listOxygen ;
            listXOxyGen.clear();
            listYOxyGen.clear();
            listYHeartRate.clear();
            if(currentIndex == R.id.rb_oxy_sop){
                for(int i = 0 ; i < getlist.size(); i++){
                    OxyDeviceDataBean model = getlist.get(i);
                    listXOxyGen.add(DateUtil.getLongToDate(model.getPosttime() + "", "yyyy-MM-dd HH:mm:ss")+"");//时间轴
                    listYOxyGen.add((float)model.getSp2());//血痒值轴
                    listYHeartRate.add((float)model.getRate());//脉搏值轴
                }
                refreshView(listXOxyGen,listYOxyGen,currentIndex);
            }
            if(getlist != null){
                tvTabHigh.setText(getlist.get(0 ).getSp2() + "");//赋值
                tvTabLow.setText(getlist.get(0).getRate() + "");//赋值
                tvTypeValue.setText(getlist.get(0).getSp2() + "");
            }
        }
    }

    /**
     * 初始化绑定设备弹窗
     */
    private void showPop() {
        MenuPopupWindow pop = new MenuPopupWindow(this, PreferenceHelper.getString(PreferenceHelper.Oxygen_NAME, ""));
        pop.showAsDropDown(titlebarRightView);
        pop.setMyHandInputVisibile(View.GONE);
        pop.setOnMenuItemClickListener(new OnMyClickListener() {
            @Override
            public void onClick(int position, String flag) {
                if (R.id.ll_bind_device == position) {
                    if (PreferenceHelper.getBoolean(PreferenceHelper.Oxygen_IS_BING, false)) {
                        //TODO 解绑操作
                        PreferenceHelper.putBoolean(PreferenceHelper.Oxygen_IS_BING, false);
                        PreferenceHelper.putString(PreferenceHelper.Oxygen_ADDRESS, "");
                        PreferenceHelper.putString(PreferenceHelper.Oxygen_NAME, "");
                        showToast("解绑成功");
                        mBluetoothLeService.close();
                    } else {
                        scanLeDevice(true);
                    }
                } else if (R.id.tv_manual_input == position) {
                } else if (R.id.tv_loadl_input == position) {
                    ActivityUtils.showActivity(BloodOxygenActivity.this, MyShopStoreActivity.class);
                }
            }
        });
        /**
         * 扫描蓝牙设备
         *
         * @param enable
         */
    }

    private void scanLeDevice(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (enable) {
                showLoading("查找设备中..");
                devices.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                // Stops scanning after a pre-defined scan period.
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            hideLoading();
                            showBluetoothNames();
                        }
                    }
                }, INTERVAL_TIME);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                try {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } catch (Exception e) {
                }
            }
        }
    }

    private void showBluetoothNames() {
        if (devices.size() <= 0) {
            // new MaterialDialog.Builder(this).title("提示").content("没有发现体温器噢~").positiveText("确定").show();
            Util.showNotHasFountDeviced(BloodOxygenActivity.this);
            return;
        }
        String[] deviceNames = new String[devices.size()];
        for (int i = 0; i < devices.size(); i++) {
            String address = devices.get(i).getAddress();
            deviceNames[i] = "血氧仪-" + address.replace(":", "");
        }
        //mLeScanCallback 将搜索结果添加到集合中
        if(!isFinishing()) {
            new MaterialDialog.Builder(this)
                    .title("血氧仪")
                    .items(deviceNames)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//                        mBluetoothLeService.connect(devices.get(which).getAddress());
                            PreferenceHelper.putBoolean(PreferenceHelper.Oxygen_IS_BING, true);
                            //PreferenceHelper.putString(PreferenceHelper.Oxygen_NAME, "血氧仪-" + devices.get(which).getAddress());
                            PreferenceHelper.putString(PreferenceHelper.Oxygen_NAME, "血氧仪-" + devices.get(which).getAddress().replace(":", ""));
                            PreferenceHelper.putString(PreferenceHelper.Oxygen_ADDRESS, devices.get(which).getAddress());
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        //线形图  group  实例化
        provider.getOxygenHistory(1 + "", 15 + "", OXYGENTION_HISTORY);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        mBluetoothLeService.close();
        mBluetoothLeService = null;
    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    /**
     * 机器测量( :  开始测量)
     */
    private void measureDataByMeachine(String address) {
        //开始测量
        mBluetoothLeService.connect( address);
    }
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            isTimeFinish = true;
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            isTimeFinish = false;
        }
    }
}
